var express = require("express");
var router = express.Router();
var multer = require("multer");
var path = require("path");

/**
 * @swagger
 * tags:
 *   name: File
 *   description: 文件上传与下载
 */

// 设置文件存储位置
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, path.join(__dirname, "../public"));
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + "-" + file.originalname);
  },
});
var upload = multer({ storage: storage });

/**
 * @swagger
 * /file/upload:
 *   post:
 *     tags: [File]
 *     summary: 上传文件
 *     requestBody:
 *       required: true
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               file:
 *                 type: string
 *                 format: binary
 *     responses:
 *       200:
 *         description: 上传成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 filename:
 *                   type: string
 *                   example: 1694444444444-test.txt
 *                 path:
 *                   type: string
 *                   example: /public/1694444444444-test.txt
 *       400:
 *         description: 未上传文件
 */
router.post("/upload", upload.single("file"), function (req, res) {
  if (!req.file) {
    return res.status(400).json({ error: "未上传文件" });
  }
  res.json({
    filename: req.file.filename,
    path: "/public/" + req.file.filename,
  });
});

/**
 * @swagger
 * /file/download/{filename}:
 *   get:
 *     tags: [File]
 *     summary: 下载文件
 *     parameters:
 *       - in: path
 *         name: filename
 *         required: true
 *         schema:
 *           type: string
 *         description: 文件名
 *     responses:
 *       200:
 *         description: 文件内容
 *         content:
 *           application/octet-stream:
 *             schema:
 *               type: string
 *               format: binary
 *       404:
 *         description: 文件未找到
 */
router.get("/download/:filename", function (req, res) {
  var filename = req.params.filename;
  var filePath = path.join(__dirname, "../public", filename);
  res.download(filePath, filename, function (err) {
    if (err) {
      res.status(404).json({ error: "文件未找到" });
    }
  });
});

module.exports = router;
